package com.example.demo.controller;

import com.example.demo.entity.ChatMessage;
import com.example.demo.mapper.ChatMessageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

@Controller
public class AgentController {

    private final ChatMessageMapper chatMessageMapper; // 替换原来的messageRepository
    private final SimpMessagingTemplate messagingTemplate;
    @Autowired
    public AgentController(ChatMessageMapper chatMessageMapper, SimpMessagingTemplate messagingTemplate) {
        this.chatMessageMapper = chatMessageMapper;
        this.messagingTemplate = messagingTemplate;
    }




    @MessageMapping("/agent/reply")
    public void handleAgentReply(ChatMessage message) {
        // 1. 通过MyBatis保存消息
//        System.out.println("客服：" + message);
        message.setTimeStamp(LocalDateTime.now());
        chatMessageMapper.insertMessage(message);

        // 2. 推送给用户
        messagingTemplate.convertAndSend(
            "/topic/user/" + message.getUserId(),
            message
        );

    }

    @GetMapping("/api/active-users")
    public List<String> getActiveUsers() {
        return chatMessageMapper.selectActiveUserIds(
            Instant.now().minus(1, ChronoUnit.HOURS)
        );
    }
}
